import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Button,
  Menu, Dropdown, Icon,
  Divider, message, Modal,
} from 'antd';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import UpdateForm from './createFrom';
import SelectEnterprise from './selectEnterprise';
import DescView from './descView';
import styles from '../UserManage.less';
import { powerBtnFunc } from '@/utils/utils';

const FormItem = Form.Item;

@connect(({ AccountManage, loading }) => ({
  AccountManage,
  loading: loading.models.AccountManage,
}))

@Form.create()
class UserManage extends PureComponent {

  constructor(props) {
    super(props);
    this.state = {
      SelectComView: false,
      modalVisible: false,
      updateModalVisible: false,
      lookDescView: false,
      selectedRows: {},
      formValues: {},
      searchEnterpriseValues: {},
      pagination: {
        pageNo: 1,
        pageSize: 15,
      },
    };
  }


  columns = [
    {
      title: '账户编号',
      dataIndex: 'accountNo',
      key: 'accountNo',
    },
    {
      title: '用户名称',
      dataIndex: 'userName',
      key: 'userName',
    },
    {
      title: '手机号',
      dataIndex: 'mobile',
      key: 'mobile',
    },

    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },

    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: val => <span>{val === 1 ? '启用' : '停用'}</span>,
    },
    {
      title: '操作',
      key: 'dataIndex',
      render: (text, record) => {
        return (
          <Fragment>
            {
              powerBtnFunc(
                '100130',
                [<a key={'view'} onClick={() => this.handleLookDesc(true, record)}>查看</a>,
                  <Divider key={'Divider'} type="vertical"/>],
              )
            }
            {
              powerBtnFunc(
                '100133',
                [<a key={'edit'} onClick={() => this.handleUpdateModalVisible(true, record)}>修改</a>,
                  <Divider key={'Divider'} type="vertical"/>],
              )
            }
            {
              powerBtnFunc('100134', [
                <a key={'status'} onClick={() => this.handleStatus(record)}>{record.status === 1 ? '停用' : '启用'}</a>,
                <Divider key={'Divider'} type="vertical"/>,
              ])
            }
            {
              powerBtnFunc('100184',
                [<a key={'bind'} onClick={() => this.handleBindEnterprise(true, record)}>关联企业</a>,
                  <Divider key={'Divider'} type="vertical"/>],
              )
            }
            {
              powerBtnFunc('100135',
                [<a key={'del'} onClick={() => this.handleMenuClick(record)}>删除</a>],
              )
            }

          </Fragment>
        );
      },
    },
  ];


  componentDidMount() {
    const { dispatch } = this.props;
    const { pagination } = this.state;
    dispatch({
      type: 'AccountManage/getDept',
      payload: {},
    });
    //请求用户列表
    dispatch({
      type: 'AccountManage/fetch',
      payload: pagination,
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    this.setState({
      pagination: {
        pageNo: pagination.current,
        pageSize: 15,
      },
    });
    const params = {
      pageNo: pagination.current,
      pageSize: 15,
      ...formValues,
    };
    dispatch({
      type: 'AccountManage/fetch',
      payload: params,
    });
  };
  //重置
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'AccountManage/fetch',
      payload: {},
    });
  };


  handleMenuClick = e => {
    const { dispatch } = this.props;
    const { pagination } = this.state;
    Modal.confirm({
      title: '确认',
      content: '确定删除该用户吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        dispatch({
          type: 'AccountManage/remove',
          payload: {
            key: e.accountNo,
          },
          callback: (res) => {
            if (res.code === 200) {
              message.success('操作成功');
              dispatch({
                type: 'AccountManage/fetch',
                payload: pagination,
              });
            } else {
              message.error(res.errMsg);
            }
          },
        });
      },
    });

  };


  //搜索
  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
      };
      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'AccountManage/fetch',
        payload: values,
      });
    });
  };
  //新建显示窗口
  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
      updateModalVisible: !!flag,
      selectedRows: {},
    });
  };
  //修改
  handleUpdateModalVisible = (flag, record) => {
    this.setState({
      updateModalVisible: !!flag,
      modalVisible: !flag,
      selectedRows: record,
      formVals: record,
    }, () => {
      if (!!flag) {
        const { dispatch } = this.props;
        dispatch({
          type: 'AccountManage/getDesc',
          payload: { accountNo: record.accountNo },
        });
      }
    });
  };
  //查看
  handleLookDesc = (flag, record) => {
    this.setState({
      lookDescView: !!flag,
      selectedRows: record,
    }, () => {
      if (!!flag) {
        const { dispatch } = this.props;
        dispatch({
          type: 'AccountManage/getDesc',
          payload: { accountNo: record.accountNo },
        });
      }
    });
  };
  searchEnterprise = (values) => {
    const { dispatch } = this.props;
    const { selectedRows } = this.state;
    this.setState({
      searchEnterpriseValues: values,
    });
    dispatch({
      type: 'AccountManage/enterpriseList',
      payload: {
        ...values,
        accountNo: selectedRows.accountNo,
      },
    });
  };

  handleStatus = (row) => {
    const { dispatch } = this.props;
    const { pagination } = this.state;
    Modal.confirm({
      title: `确定`,
      content: `你确定${row.status === 1 ? '停用' : '启用'}该账户吗?`,
      okText: '确认',
      cancelText: '取消',
      onOk() {
        dispatch({
          type: 'AccountManage/status',
          payload: {
            accountNo: row.accountNo,
            status: row.status === 1 ? 2 : 1,
          },
          callback: (res) => {
            if (res.code === 200) {
              message.success('操作成功');
              dispatch({
                type: 'AccountManage/fetch',
                payload: pagination,
              });
            } else {
              message.error(res.errMsg);
            }
          },
        });
      },
      onCancel() {
        console.log('Cancel');
      },
    });

  };

  handleBindEnterprise = (flag, record) => {
    const { dispatch } = this.props;
    this.setState({
      SelectComView: !!flag,
      selectedRows: record,
    }, () => {
      if (flag) {
        dispatch({
          type: 'AccountManage/enterpriseList',
          payload: {
            accountNo: record.accountNo,
            pageSize: 15,
          },
          callback(res) {
            if (res.msg.length === 0) {
              message.error('请增加企业');
            }
          },
        });
      }
    });
  };

  handleSelectEnterprise = (flag, record) => {
    const { pagination } = this.state;
    this.setState({
      SelectComView: !!flag,
    }, () => {
      let arr = [];
      record.data.map((item) => {
        if (item.checked) {
          arr.push(item.enterpriseNo);
        }
      });
      if (!flag && arr.length > 0) {
        const { dispatch } = this.props;
        const { selectedRows } = this.state;
        dispatch({
          type: 'AccountManage/bindEnterprise',
          payload: { enterpriseNoList: arr, accountNo: selectedRows.accountNo },
          callback(res) {
            if (res.code === 200) {
              message.success('关联成功');
              dispatch({
                type: 'AccountManage/fetch',
                payload: pagination,
              });
            } else {
              message.error(res.errMsg);
            }
          },
        });
      }
    });
  };

  // 新建请求
  handleAdd = fields => {
    const { dispatch } = this.props;
    dispatch({
      type: 'AccountManage/add',
      payload: fields,
      callback: (response) => {
        this.handleModalVisible();
        dispatch({
          type: 'AccountManage/fetch',
        });
      },
    });

  };
  // 修改请求
  handleUpdate = fields => {
    const { pagination } = this.state;
    const { dispatch } = this.props;
    dispatch({
      type: 'AccountManage/update',
      payload: fields,
      callback: () => {
        dispatch({
          type: 'AccountManage/fetch',
          payload: pagination,
        });
        this.handleUpdateModalVisible(false, []);
      },
    });

  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={6} sm={24}>
            <FormItem label="企业名称">
              {getFieldDecorator('enterpriseName')(<Input placeholder="请输入企业名称"/>)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="手机号">
              {getFieldDecorator('mobile')(<Input placeholder="请输入手机号"/>)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="用户名称">
              {getFieldDecorator('entUserName')(<Input placeholder="请输入用户名称"/>)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
        <span className={styles.submitButtons}>
        <Button type="primary" htmlType="submit">
        查询
        </Button>
        <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
        重置
        </Button>

        </span>
          </Col>
        </Row>
      </Form>
    );
  }


  render() {
    const { AccountManage: { data, userDesc, companyList = {} }, loading } = this.props;
    const { selectedRows, modalVisible, updateModalVisible, lookDescView, SelectComView } = this.state;

    const parentMethods = {
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible,
      handleUpdateModalVisible: this.handleUpdateModalVisible,
      handleUpdate: this.handleUpdate,
    };

    return (
      <PageHeaderWrapper title="账户管理">
        <Card bordered={false}>

          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderSimpleForm()}</div>
            <div className={styles.tableListOperator}>
              {
                powerBtnFunc('100132',
                  <Button icon="plus" key={'create'} type="primary"
                          onClick={() => this.handleModalVisible(true)}>
                    新建
                  </Button>)
              }
            </div>
            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={data ? data : []}
              rowKey={'accountNo'}
              rowSelectHide={true}
              columns={this.columns}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        <DescView
          handleLookDesc={this.handleLookDesc}
          selectedRows={userDesc ? userDesc : ''}
          lookDescView={lookDescView}/>

        <UpdateForm
          {...parentMethods}
          updateModalVisible={updateModalVisible}
          modalVisible={modalVisible}
          values={selectedRows}
        />

        {
          Object.keys(companyList).length > 0 ?
            <SelectEnterprise
              SelectComView={SelectComView}
              selectedRows={selectedRows}
              companyList={companyList}
              searchEnterprise={this.searchEnterprise}
              handleSelectEnterprise={this.handleSelectEnterprise}
              handleBindEnterprise={this.handleBindEnterprise}
            /> : ''
        }

      </PageHeaderWrapper>
    );
  }
}

export default UserManage;
